package com.zhiwen.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

/**
 * @Auther: wuzhiwen
 * @Date: 2018/12/28 09:15
 * @Description:
 */
public class AIOServer {
    public AIOServer(int port) throws IOException {
        //监听端口
        final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
        listener.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            public void completed(AsynchronousSocketChannel result, Void attachment) {
                //接收下一个链接
                listener.accept(null, this);
                try {
                    handler(result);
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            public void failed(Throwable exc, Void attachment) {
                System.out.println("异步IO失败");
            }
        });
    }

    private void handler(AsynchronousSocketChannel result) throws ExecutionException, InterruptedException {
        ByteBuffer bytebuffer = ByteBuffer.allocate(32);
        result.read(bytebuffer).get();
        bytebuffer.flip();
        System.out.println("服务端接收" + bytebuffer.get());

    }

    public static void main(String[] args) throws InterruptedException, IOException {
        AIOServer aioServer = new AIOServer(8010);
        System.out.println("监听端口：" + 8010);
        Thread.sleep(10000);
    }

}
